package com.netty.badtcptime;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * Package Name:com.my.time
 * Description: TCP粘包场景模拟
 * Date:2016/8/24 15:02
 * Copyright (c) 2016, zhongmu@suneee.com All Rights Reserved.
 */
public class TimeClientHandler extends ChannelHandlerAdapter {



    private final byte[] req;
    private int counter;

    //create a client-side handler
    public TimeClientHandler() {
         req = ("QUERY TIME ORDER "+System.getProperty("line.separator")).getBytes();
        //Unpooled 用来创建一个新的byteBuf ,长度为req的长度
//        firstMessage = Unpooled.buffer(req.length);
//        firstMessage.writeBytes(req);

    }

    //建立链路成功时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf message = null;
        //发送100次消息
        for (int i=0;i<100;i++){
            message = Unpooled.buffer(req.length);
            message.writeBytes(req);
            ctx.writeAndFlush(message);

        }

    }

    //服务端返回应答时调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;

        byte[] req = new byte[byteBuf.readableBytes()];

        byteBuf.readBytes(req);

        String body = new String(req, "UTF-8");

        System.out.println("Now is :" + body +";\n the counter is" + ++counter);


    }

    //异常时调用
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
